#include <stdio.h>
#include <ctype.h>
#include "poker_defs.h"


const char StdDeck_rankChars[] = "23456789TJQKA";
const char StdDeck_suitChars[] = "hdcs";


int 
StdDeck_cardToString(int cardIndex, char *outString) {
  *outString++ = StdDeck_rankChars[StdDeck_RANK(cardIndex)];
  *outString++ = StdDeck_suitChars[StdDeck_SUIT(cardIndex)];
  *outString   = '\0';

  return 2;
}


int 
StdDeck_stringToCard(char *inString, int *cardIndex) {
  char *p;
  int rank, suit;

  p = inString;
  for (rank=StdDeck_Rank_FIRST; rank <= StdDeck_Rank_LAST; rank++) 
    if (StdDeck_rankChars[rank] == toupper(*p))
      break;
  if (rank > StdDeck_Rank_LAST)
    goto noMatch;
  ++p;
  for (suit=StdDeck_Suit_FIRST; suit <= StdDeck_Suit_LAST; suit++) 
    if (StdDeck_suitChars[suit] == tolower(*p))
      break;
  if (suit > StdDeck_Suit_LAST)
    goto noMatch;
  *cardIndex = StdDeck_MAKE_CARD(rank, suit);
  return 2;

 noMatch:
  /* Didn't match anything, return failure */
  return 0;
}


int
StdDeck_maskToCards(void *cardMask, int cards[]) {
  int i, n=0;
  StdDeck_CardMask c = *((StdDeck_CardMask *) cardMask);

  for (i=StdDeck_N_CARDS-1; i >= 0; i--) 
    if (StdDeck_CardMask_CARD_IS_SET(c, i)) 
      cards[n++] = i;

  return n;
}


#if 0
int 
StdDeck_stringToMask(char *inString, StdDeck_CardMask *outMask) {
  char *p;
  int n=0, rank, suit, card;

  StdDeck_CardMask_RESET(*outMask);
  for (p=inString; p < inString + strlen(inString); p++) {
    if (*p == ' ')
      continue;
    for (rank=StdDeck_Rank_FIRST; rank <= StdDeck_Rank_LAST; rank++) 
      if (StdDeck_rankChars[rank] == toupper(*p))
        break;
    if (rank > StdDeck_Rank_LAST)
      break;
    ++p;
    for (suit=StdDeck_Suit_FIRST; suit <= StdDeck_Suit_LAST; suit++) 
      if (StdDeck_suitChars[suit] == tolower(*p))
        break;
    if (suit > StdDeck_Suit_LAST)
      break;
    ++p;
    card = StdDeck_MAKE_CARD(rank, suit);
    StdDeck_CardMask_SET(*outMask, card);
    ++n;
  }
    
  return n;
}
#endif

#if 0
int 
StdDeck_CardMask_nBitsSet(StdDeck_CardMask cards) {
  return 0;
}
#endif

Deck StdDeck = { 
  StdDeck_N_CARDS, 
  "StandardDeck", 
  StdDeck_cardToString, 
  StdDeck_stringToCard,
  StdDeck_maskToCards 
};

